from fastapi import APIRouter, Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from sqlalchemy.orm import Session
from api.dep import get_current_active_user
from db_manage.conversation_manage import create_conversation, get_conversation, get_conversations, delete_conversation
from database import get_db
from models import SysUser
from services.conversation_service import delete_conversation_and_messages

router = APIRouter(prefix="/api", tags=["conversations"])
security = HTTPBearer()
class ConversationForm(BaseModel):
    title: str
@router.post("/conversations")
def create_conversation_route(
    conversation: ConversationForm,
    credentials: HTTPAuthorizationCredentials = Depends(security),
    current_user: SysUser = Depends(get_current_active_user),
    db: Session = Depends(get_db)):
    return create_conversation(db=db, title=conversation.title, user_id=current_user.id)

@router.get("/conversations")
def read_conversations(
    skip: int = 0, 
    limit: int = 10,
    credentials: HTTPAuthorizationCredentials = Depends(security),
    current_user: SysUser = Depends(get_current_active_user),
    db: Session = Depends(get_db)):
    return get_conversations(db=db, skip=skip, limit=limit, user_id=current_user.id)

@router.delete("/conversations/{conversation_id}")
def delete_conversation_route(
    conversation_id: int,
    credentials: HTTPAuthorizationCredentials = Depends(security),
    current_user: SysUser = Depends(get_current_active_user),
    db: Session = Depends(get_db)
    ):
    return delete_conversation_and_messages(db=db, conversation_id=conversation_id, user_id=current_user.id)

@router.get("/conversations/{conversation_id}")
def read_conversation(
    conversation_id: int,
    current_user: SysUser = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    return get_conversation(db=db, conversation_id=conversation_id, user_id=current_user.id)
